import classNames from 'classnames';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import React from 'react';
import { NavLink, withRouter } from 'react-router-dom';
import { Avatar, Button, Calendar, Icon, NavBar, Popover, SegmentedControl, Toast, Tools } from 'weaver-mobile';
import zhCN from 'weaver-mobile/lib/calendar/locale/zh_CN';
import enUS from 'weaver-mobile/lib/calendar/locale/en_US';
import { getRequest } from '../../../common/getRequest';
import If, { Else, Then, When } from '../../../common/if';
import Loading from '../../../common/loading';
import { dateType } from '../../../components/form/statistics/typeof';
import { TIPS_MSG } from '../../../constants/form';
import _u from '../../../utils';
import AppChartView from "../../app/analysis/ChartView";
import SearchAdvanced from './SearchAdvanced';
import './index.less';
import ListView from '../../../common/list-view';
import WeekList from './WeekList';
import _ from 'lodash';

const getLabel = Tools.getLabel; 
const { BYDAY, BYWEEK } = dateType;

@inject('formStatisticsStore')
@withRouter
@observer
export default class Statistics extends React.Component {
  originbodyScrollY = document.getElementsByTagName('body')[0].style.overflowY;
  constructor(props) {
    super(props);

    const appid = props.match.params.id;

    this.store = props.formStatisticsStore;
    this.store.init(appid);
    this.state = {
      selectedIndex: 0,
      isShowSelect: false,
      isShowDate: false,
      selectedDate: '',
      advanceConditions: {
        userId: '',
        users: [],
        deptId: '',
        depts: []
      },
      weekListVisible: false
    };

    if (getRequest().backBtnAble === 'true') {
      window.backBtnAble = true;
    }
  }

  onChange = (e) => {
    const selectedIndex = e.nativeEvent.selectedSegmentIndex;
    const { setDate, dateType, date } = this.store;

    this.setState({ selectedIndex });
    setDate(dateType, date, selectedIndex, true);
  }

  renderRow = (rowData) => {
    const { appMsg: { shortKey } } = this.store;
    let url = `/edc/formview/${shortKey}?data=${rowData.id}`;
    let target = '_blank';
    const backBtnAble = window.backBtnAble;

    if (backBtnAble) { //判断是否在em7中打开，添加返回按钮 
      url = url + '&backBtnAble=true';
      target = '_self';
    }

    return (
      <a onClick={() => this.goto(url, target)} className='statistics-row-item'>
        <Avatar url={rowData.messageurl || rowData.wxheadimgurl} name={rowData.creatorspan} userId={rowData.creator}/>
        <div className='person-info'>
          <div className='lastname'>{rowData.creatorspan || rowData.wxnickname}</div>
          <div className='create-date'>{`${getLabel(523283, '提交于')}${rowData.createDate} ${rowData.createTimespan}`}</div>
        </div>
      </a>
    );
  }

  goto = (url, target) => {
    if (target === '_blank') {
      window.open(url);
    } else {
      window.location.href = url;
    }
  }

  hideMasker = () => this.setState({ isShowSelect: false, weekListVisible: false });
  toggleSelect = () => this.setState({ isShowSelect: !this.state.isShowSelect });

  renderText = () => {
    const { date, dateType } = this.store;
    let showText = '';

    if (dateType === BYWEEK) {
      const startDateText = date[0].split('-');
      const endDateText = date[1].split('-');

      showText = Number(startDateText[1]) + getLabel(523284, '月') + Number(startDateText[2]) + getLabel(523285, '日') + ' ~ ' + Number(endDateText[1]) + getLabel(523284, '月') + Number(endDateText[2]) + getLabel(523285, '日');
    } else {
      const dateText = date.split('-');
      if (dateText.length === 3) {
        showText = Number(dateText[1]) + getLabel(523284, '月') + Number(dateText[2]) + getLabel(523285, '日');
      }
    }

    if (dateType === BYDAY)  {
      return (
        <div className='navbar-date-title' onClick={() => this.setState({ isShowDate: true })}>
          {showText}
          <Icon type="calendar" size='xxs' />
        </div>
      )
    } else if (dateType === BYWEEK) {
      return (
        <div className='navbar-date-title' onClick={() => this.setState({ weekListVisible: true })}>
          {showText}
          <Icon type="calendar" size='xxs' />
        </div>
      );
    };

    return getLabel(523286, '全部日期');
  }

  onAdvanceSearch = conditions => {
    const {
      dateType,
      deptId,
      depts,
      selectedDate,
      userId,
      users
    } = conditions;
    const { selectedIndex } = this.state;
    const { setDate, appMsg, dateType: curType, date: curDate } = this.store;
    const advanceConditions = { deptId, depts: toJS(depts), userId, users: toJS(users) };
    const adContion = { deptId, userId };
    let date = curDate;

    if (dateType === BYWEEK) {
      date = selectedDate;

      this.setState({ advanceConditions, selectedDate: date });
    } else if (dateType === BYDAY) {
      date = selectedDate || _u.dateFormat('YY-mm-dd', new Date());
      this.setState({ advanceConditions, selectedDate });
    }

    setDate(dateType, date, selectedIndex, true, adContion);
  }

  onConfirm = (startDate, endDate) => {
    const { setDate, dateType } = this.store;
    const { selectedIndex } = this.state;
    const date = _u.dateFormat('YY-mm-dd', startDate);

    setDate(dateType, date, selectedIndex);
    this.setState({ isShowDate: false, selectedDate: _u.dateFormat('YY-mm-dd', startDate) });
  }

  renderBeforeNext = (next) => {
    const { appMsg = {}, date, setDate, dateType } = this.store;
    const startDate = appMsg.createDate || '1990-01-01';
    const endDate = _u.dateFormat('YY-mm-dd', new Date());

    if (dateType === BYWEEK) {
      let curStartDate = new Date(date[0]);
      let curEndDate = new Date(date[1]);

      curStartDate.setDate(curStartDate.getDate() + 1 - curStartDate.getDay());

      if (curEndDate.getDay() === 0) {
        curEndDate = curEndDate;
      } else {
        curEndDate.setDate(curEndDate.getDate() + 7 - curEndDate.getDay());
      }

      if (next === -7 && new Date(startDate).getTime() >= curStartDate.getTime()) {
        Toast.offline(getLabel(523287, '统计周不能小于表单创建周'), 0.8);
        return;
      }
      if (next === 7 && new Date(endDate).getTime() <= curEndDate.getTime()) {
        Toast.offline(getLabel(523288, '统计周不能大于本周'), 0.8);
        return;
      }

      const nextStartDate = new Date(curStartDate.getTime() + next * 24 * 60 * 60 * 1000);
      const nextEndDate = new Date(curEndDate.getTime() + next * 24 * 60 * 60 * 1000);
      const newDate = [_u.dateFormat('YY-mm-dd', nextStartDate), _u.dateFormat('YY-mm-dd', nextEndDate)];

      setDate(BYWEEK, newDate, this.state.selectedIndex);
      this.setState({ selectedDate: newDate });
    } else if (dateType === BYDAY) {
      const curDate = new Date(date);
     
      if (next === -1 && startDate >= date) {
        Toast.offline(getLabel(523289, '统计日期不能小于表单创建日期'), 0.8);
        return;
      }
      if (next === 1 && endDate <= date) {
        Toast.offline(getLabel(523290, '统计日期不能大于今天'), 0.8);
        return;
      }

      const newDate = _u.dateFormat('YY-mm-dd', new Date(curDate.getTime() + next * 24 * 60 * 60 * 1000));

      this.setState({ selectedDate: newDate });
      setDate(BYDAY, newDate, this.state.selectedIndex);
    }
  }

  getDateExtra = date => {
    const { appMsg, dateType, eachDayCount = {} } = this.store;
    const dateStr = _u.dateFormat('YY-mm-dd', date);
    const { submitted, shouldSubmit } = eachDayCount;
    const startDate = appMsg.createDate || '1990-01-01';
    const startTime = new Date(startDate).getTime();
    const endTime = new Date().getTime();
    const currentTime = new Date(dateStr).getTime();
    const disabled = currentTime < startTime || currentTime > endTime;

    if (submitted && submitted[dateStr]) {
      const showNumber = Number(submitted[dateStr]);
      if (shouldSubmit > 0) {
        return { info: <span><span style={shouldSubmit !== showNumber ? { color: 'red' } : {}}>{showNumber}</span>/{shouldSubmit}</span>, disable: disabled };
      } else {
        return { info: showNumber, disable: disabled };
      }
    }

    return { disable: disabled };
  }

  getNavBar = () => {
    const { appMsg = {}, date, dateType } = this.store;
    const { isShowSelect, advanceConditions, weekListVisible } = this.state;
    const { userId, deptId } = advanceConditions;
    const startDate = appMsg.createDate || '1990-01-01';
    const endDate = _u.dateFormat('YY-mm-dd', new Date());
    let curStartDate = _.isArray(toJS(date)) ? new Date(date[0]) : new Date(date);
    let curEndDate = _.isArray(toJS(date)) ? new Date(date[1]) : new Date(date);

    if (dateType === BYWEEK) {
      curStartDate.setDate(curStartDate.getDate() + 1 - curStartDate.getDay());

      if (curEndDate.getDay() === 0) {
        curEndDate = curEndDate;
      } else {
        curEndDate.setDate(curEndDate.getDate() + 7 - curEndDate.getDay());
      }
    }

    const beforeIconCls = classNames('navbar-date-before', {
      'icon-disabled': new Date(startDate).getTime() >= curStartDate.getTime()
    });
    const nextIconCls = classNames('navbar-date-next', {
      'icon-disabled': new Date(endDate) <= curEndDate.getTime()
    });

    return (
      <NavBar
        mode="dark"
        rightContent={[
          <div className={classNames('navbar-date-ellipsis', { 'navbar-has-condition' : userId || deptId })}>
            <Icon type="filter-o" onClick={this.toggleSelect}/>
          </div>
        ]}
      > 
        {(isShowSelect || weekListVisible) ? <div 
          className={classNames({'date-masker': isShowSelect, 
          'week-masker': weekListVisible, 
          'week-masker-has-back': weekListVisible && window.backBtnAble})}></div> : null }
        {dateType === BYDAY && <span className={beforeIconCls} onClick={() => this.renderBeforeNext(-1)}>{getLabel(523291, '前一天')}</span>}
        {dateType === BYWEEK && <span className={beforeIconCls} onClick={() => this.renderBeforeNext(-7)}>{getLabel(523292, '前一周')}</span>}
        {this.renderText()}
        {dateType === BYDAY && <span className={nextIconCls} onClick={() => this.renderBeforeNext(1)}>{getLabel(523293, '后一天')}</span>}
        {dateType === BYWEEK && <span className={nextIconCls} onClick={() => this.renderBeforeNext(7)}>{getLabel(523294, '后一周')}</span>}
      </NavBar>
    );
  }

  renderDataAndChart = () => {
    const { submitResult, submittedStore, chartStore } = this.store;
    const { widgets, noChart, isInit: isChartInit, timer } = chartStore;
    const { selectedIndex } = this.state;

    return (
      <If condition={selectedIndex === 0}>
        <Then>
          <If condition={submitResult.total !== 0}>
            <Then>
              <div className='statistics-list'>
                <ListView
                  store={submittedStore.list}
                  renderRow={this.renderRow}
                />
              </div>
            </Then>
            <Else>
              <div className='statistics-no-data'>
                <Icon type={'no-data'} />
                <span>{getLabel(523295, '暂无提交记录')}</span>
              </div>
            </Else>
          </If>

        </Then>
        <Else>
          <div className='statistics-chart'>
            <AppChartView
              widgets={widgets}
              noChart={noChart}
              loading={!isChartInit}
              timer={timer}
            />
          </div>
        </Else>
      </If>
    );
  }

  onCancel = () => {
    this.setState({ isShowDate: false })
  }

  onSelectWeek = date => {
    const { setDate , dateType } = this.store;
    const { selectedIndex } = this.state;

    setDate(dateType, date, selectedIndex);
    this.setState({ weekListVisible: false, selectedDate: date });
  }

  render() {
    const { appMsg = {}, appid, submitResult, onFillinEnable, fillinEnable, date, dateType, loading } = this.store;
    const { selectedIndex, isShowSelect, isShowDate, selectedDate, advanceConditions, weekListVisible } = this.state;
    const backBtnAble = window.backBtnAble;
    const search = JSON.parse(window.localStorage.getItem('search'));
    const localLangue = window.localStorage.getItem('languageidweaver');
    let lan = zhCN;
    if (localLangue == '8') {
      lan = enUS;
    }

    let selectDate = [];

    if (dateType === BYDAY) {
      selectDate = [new Date(date || selectedDate)];
    } 

    let timeShowText = '';
    if (appMsg.createDate) {
      const dateText = appMsg.createDate.split('-');
      if (dateText.length === 3) {
        timeShowText = dateText[1] + getLabel(523284, '月') + dateText[2] + getLabel(523285, '日');
      }
    }

    return (
      <div className='wea-edc-mobile-statistics'>
        <If condition={loading}>
          <Then>
            <Loading loading={true} content={TIPS_MSG.LOADING} className='statistics-loading' />
          </Then>
          <Else>
            <If condition={backBtnAble}>
              <div className='edc-mobile-statistics-back'>
                <NavLink to={`/form${search}`}>
                  <Icon type='arrow-left' size='md' />
                </NavLink>
              </div>
            </If>
            {this.getNavBar()}
            <div className={classNames('main', { 'main-has-back': backBtnAble })}>
              <div className='header'>
                <div className='title'>{appMsg.name}</div>
                <When condition={appMsg.rightLevel === 2}>
                  <Button className='fill' onClick={onFillinEnable}>{fillinEnable ? getLabel(523248, '停止收集') : getLabel(523249, '继续收集')}</Button>
                </When>
              </div>
              <div className='msg'>
                <div>
                  <span>{getLabel(523296, '创建人')}：</span>
                  <span>{appMsg.creator}</span>
                  <span>{timeShowText}</span>
                </div>
              </div>
              <div className='submit-count'>
                <div>
                  <span className='result-write-member'>
                    <span className='number'>
                      <span>{submitResult.submitted || 0}</span>
                      {
                        submitResult.shouldSubmit !== -1 &&
                        <span>/{submitResult.shouldSubmit}</span>
                      }
                      <span style={{ 'fontSize': 12 }}> {getLabel(523264, '人填写')}</span>
                    </span >
                  </span>

                  <span><span className='number'>{submitResult.total || 0}</span> {getLabel(523297, '份结果')}</span>
                </div>
                {
                  submitResult.unSubmit > 0 ?
                    <div className='no-wrtie-link'>
                      <NavLink to={{ pathname: `/form/statistics/unsubmit/${appid}`, date: dateType === BYDAY ? date : '' }}>{submitResult.unSubmit}{getLabel(523316, '人未填写')}</NavLink>
                    </div> : null
                }
              </div>
              <div className='result-analysis'>
                <SegmentedControl
                  values={[getLabel(523298, '提交情况'), getLabel(523299, '数据分析')]}
                  onChange={this.onChange}
                  selectedIndex={selectedIndex}
                />
              </div>
              {this.renderDataAndChart()}
            </div>
            <Calendar
              enterDirection={'vertical'}
              onConfirm={this.onConfirm}
              onCancel={this.onCancel}
              locale={lan}
              type={'one'}
              visible={isShowDate}
              defaultValue={selectDate}
              defaultDate={selectDate[0]}
              minDate={new Date('1990-01-01')}
              maxDate={new Date()}
              getDateExtra={this.getDateExtra}
            />
            {
              (isShowSelect || weekListVisible) ?
              <div className='statistics-mask' onClick={this.hideMasker}></div>: null
            }
            <SearchAdvanced 
              visible={isShowSelect}
              onSearch={this.onAdvanceSearch}
              toggleVisible={this.toggleSelect}
              condition={{
                ...advanceConditions,
                selectedDate: toJS(date),
                dateType
              }}
            />
            <WeekList 
              visible={weekListVisible}
              onSelect={this.onSelectWeek}
            />
          </Else>
        </If>
      </div>
    );
  }
}